// Copyright 2012 Dorival de Moraes Pedroso. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "code.google.com/p/gemlab"
    "encoding/json"
)

func Pfblue2(msg string, prm ...interface{}) { fmt.Printf("[38;5;69m" +msg+"[0m", prm...) }
func Pforan (msg string, prm ...interface{}) { fmt.Printf("[38;5;202m"+msg+"[0m", prm...) }

func main() {

    // error recovery
    defer func() {
        if err := recover(); err != nil {
            fmt.Printf("[1;31mSome error has happened:\n%v[0m\n", err)
        }
    }()

    // parse flags
	flag.Parse()
	var fname string
	if len(flag.Args()) > 0 {
        fname = flag.Arg(0)
    } else {
        panic("Please, provide a filename. Ex.: meshdata.inp")
    }

    // read input file
    b, err := ioutil.ReadFile(os.ExpandEnv(fname))
    if err != nil {
        panic(fmt.Sprintf("cannot read file <%v>\n%v", fname, err))
    }

    // set data type
    type datype struct {
        Quad   bool             // quadratic?
        Nparts int              // number of partitions (>0 => domain decomposition)
        Pfull  bool             // full partition?
        Gmax   float64          // global max area?
        Uregs  *gemlab.Uregions // unstructured regions
        Sregs  *gemlab.Sregions // structured regions
        Lregs  *gemlab.Lregions // linear regions
        Vtags  *gemlab.Vtags    // vertices tags
    }

    // unmarshal file
    var dat datype
    err = json.Unmarshal(b, &dat)
    if err != nil {
        panic(fmt.Sprintf("cannot unmarshal file <%v>\n%v", fname, err))
    }

    // print input data
    Pforan("\nInput data\n")
    Pforan("==========\n")
    Pfblue2("  quad    = %v\n", dat.Quad)
    Pfblue2("  nparts  = %v\n", dat.Nparts)
    Pfblue2("  pfull   = %v\n", dat.Pfull)
    Pfblue2("  gmax    = %v\n", dat.Gmax)
    Pfblue2("  Uregs   = %v\n", dat.Uregs)
    Pfblue2("  Sregs   = %v\n", dat.Sregs)
    Pfblue2("  Lregs   = %v\n", dat.Lregs)
    Pfblue2("  Vtags   = %v\n", dat.Vtags)
    Pforan("\n")

    // file name key
    fn := filepath.Base(fname)
    if len(filepath.Ext(fn)) == 4 {
        fn = fn[:len(fn)-4]
    }

    // generate unstructured mesh
    if dat.Uregs != nil {
        err = gemlab.UmeshGen(fn, dat.Quad, dat.Nparts, dat.Pfull, dat.Gmax, dat.Uregs, dat.Lregs, dat.Vtags)
        if err != nil {
            panic(fmt.Sprintf("unstructured mesh generation failed:\n%v", err.Error()))
        }
    }

    // generate structured mesh
    if dat.Sregs != nil {
        err = gemlab.SmeshGen(fn, dat.Quad, dat.Nparts, dat.Pfull, dat.Sregs, dat.Lregs, dat.Vtags)
        if err != nil {
            panic(fmt.Sprintf("unstructured mesh generation failed:\n%v", err.Error()))
        }
    }
}
